from pymongo import MongoClient
import sys
from bson.son import SON
import pprint

TABLE = 'things'

db = MongoClient('172.24.101.183').test

tables = set(db.list_collection_names())
if not TABLE in tables:
    result = db[TABLE].insert_many([{"x": 1, "tags": ["dog", "cat"]},

                                    {"x": 2, "tags": ["cat"]},

                                    {"x": 2, "tags": ["mouse", "cat", "dog"]},

                                    {"x": 3, "tags": []}])

    print(result.inserted_ids)

pipeline = [

    {"$unwind": "$tags"},

    {"$group": {"_id": "$tags", "count": {"$sum": 1}}},

    # {"$sort": SON([("count", -1), ("_id", -1)])},
    {"$sort": {"count": -1}},

]

pprint.pprint(list(db.things.aggregate(pipeline)))
